package com.ferry.config.server.service;

import com.alibaba.fastjson.JSON;
import com.ferry.config.server.LongPollManager;
import com.ferry.config.server.mapper.FConfigItemMapper;
import com.ferry.config.server.vo.FConfigItemDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by daiyong
 */
@Service
public class FConfigItemService {

	@Autowired
	private FConfigItemMapper fConfigItemMapper;

	public int create(String nameSpace,
					  String key,
					  String content,
					  String cUser,
					  String desc) {

		FConfigItemDO itemDO = new FConfigItemDO();
		itemDO.setNameSpace(nameSpace);
		itemDO.setfKey(key);
		itemDO.setContent(content);
		itemDO.setfDesc(desc);
		itemDO.setcUser(cUser);
		long time = System.currentTimeMillis();
		itemDO.setcTime(time);
		itemDO.setuTime(time);

		int rows =  fConfigItemMapper.insert(itemDO);

		if (rows > 0) {
			//唤醒长轮询
			Map<String, Object> updateMsg = new HashMap<String, Object>();
			updateMsg.put("key", key);
			updateMsg.put("content", content);
			updateMsg.put("maxUtime", time);
			LongPollManager.notifyDeferredResult(nameSpace, JSON.toJSONString(updateMsg));
		}

		return rows;
	}

	public List<FConfigItemDO> get(String nameSpace) {
		return fConfigItemMapper.get(nameSpace);
	}

	public int update(String nameSpace, String key, String content, String uUser, String desc) {
		FConfigItemDO itemDO = new FConfigItemDO();
		itemDO.setNameSpace(nameSpace);
		itemDO.setfKey(key);
		itemDO.setContent(content);
		itemDO.setfDesc(desc);
		itemDO.setuUser(uUser);
		long utime = System.currentTimeMillis();
		itemDO.setuTime(utime);
		int rows = fConfigItemMapper.update(itemDO);

		if (rows > 0) {
			//唤醒长轮询
			Map<String, Object> updateMsg = new HashMap<String, Object>();
			updateMsg.put("key", key);
			updateMsg.put("content", content);
			updateMsg.put("maxUtime", utime);
			LongPollManager.notifyDeferredResult(nameSpace, JSON.toJSONString(updateMsg));
		}

		return rows;
	}

	public List<FConfigItemDO> getByMaxUtime(String nameSpace, long maxUtime) {
		return fConfigItemMapper.getByMaxUtime(nameSpace, maxUtime);

	}
}
